package com.huacai.blog.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    @Value("${deepseek.api-key}")
    private String apiKey;

    private final String DEEPSEEK_URL = "https://api.deepseek.com/v1/chat/completions";

    @PostMapping("/ask")
    public JSONObject ask(@RequestBody JSONObject req) {
        String question = req.getString("question");
        if (question == null || question.trim().isEmpty()) {
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("error", "内容不能为空");
            return errorResponse;
        }

        RestTemplate rest = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", question);
        messages.add(message);

        JSONObject body = new JSONObject();
        body.put("model", "deepseek-chat");
        body.put("messages", messages);
        body.put("temperature", 0.7);

        HttpEntity<String> entity = new HttpEntity<>(body.toJSONString(), headers);
        String resp = rest.postForObject(DEEPSEEK_URL, entity, String.class);

        JSONObject out = JSONObject.parseObject(resp);
        String answer = out.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content");

        JSONObject successResponse = new JSONObject();
        successResponse.put("answer", answer.trim());
        return successResponse;
    }

    @PostMapping("/generate-summary")
    public JSONObject generateSummary(@RequestBody JSONObject req) {
        String content = req.getString("content");
        String title = req.getString("title");

        if (content == null || content.trim().isEmpty()) {
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("error", "内容不能为空");
            return errorResponse;
        }

        // 清理HTML标签，只保留文本内容
        String plainText = content.replaceAll("<[^>]+>", "");

        // 如果内容太长，截取前2000字符（避免API token限制）
        if (plainText.length() > 2000) {
            plainText = plainText.substring(0, 2000) + "...";
        }

        String prompt;
        if (title != null && !title.trim().isEmpty()) {
            prompt = "请为以下博客文章生成一个简洁的摘要（150字以内）：\n\n标题：" + title + "\n\n内容：" + plainText + "\n\n摘要：";
        } else {
            prompt = "请为以下博客文章生成一个简洁的摘要（150字以内）：\n\n" + plainText + "\n\n摘要：";
        }

        RestTemplate rest = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", prompt);
        messages.add(message);

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.3);
        requestBody.put("max_tokens", 200);

        try {
            HttpEntity<String> entity = new HttpEntity<>(requestBody.toJSONString(), headers);
            String response = rest.postForObject(DEEPSEEK_URL, entity, String.class);

            JSONObject responseJson = JSONObject.parseObject(response);
            String summary = responseJson.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content")
                    .trim();

            // 清理摘要中的可能的多余文本
            summary = summary.replaceAll("^(摘要|总结|概要)[：:]?", "").trim();

            JSONObject data = new JSONObject();
            data.put("summary", summary);

            JSONObject successResponse = new JSONObject();
            successResponse.put("code", 200);
            successResponse.put("msg", "成功");
            successResponse.put("data", data);

            return successResponse;

        } catch (Exception e) {
            e.printStackTrace();

            JSONObject errorResponse = new JSONObject();
            errorResponse.put("code", 500);
            errorResponse.put("msg", "摘要生成失败: " + e.getMessage());

            return errorResponse;
        }
    }
}